import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';

export interface PointPhoto {
  id: string;
  longitude: number;
  latitude: number;
  azimuth: number;
  originalFilename: string;
  src: string;
  thumbnailSrc: string;
  surveyId: string;
}

@Injectable()
export class PhotosService {

  constructor(
    private http: HttpClient
  ) { }

  getAllPhotos(id: string): Observable<PointPhoto[]> {
    return this.http.get(`/platform/api/survey-points/${id}/images`)
      .pipe(
        map((result: PointPhoto[]) => {
          return result.map((photo: PointPhoto) => {
            let imageSplit = [null, null];
            let name = null;
            let suffix = null;
            if(photo.originalFilename) {
              imageSplit = photo.originalFilename.split('.');
              name = imageSplit[0];
              suffix = imageSplit[1];
            }
            return {
              ...photo,
              src: `/platform/api/containers/images/download/${name}.${suffix}`,
              thumbnailSrc: `/platform/api/containers/images/download/${name}-mini.png`
            };
          });
        }),
        catchError(error => Observable.throw(error))
      );
  }
}
